package com.shu.juc;

import java.util.Collections;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author ssm
 * @version V1.0
 * @description:
 * @date 2020/7/30 10:19
 */

public class CompletableFutureTest {

    ExecutorService threadPool = Executors.newFixedThreadPool(3);

    public static void main(String[] args) throws InterruptedException {
        CompletableFutureTest test = new CompletableFutureTest();
        System.out.println(test.getPrices());
    }

    private Set<Integer> getPrices() throws InterruptedException {
        Set<Integer> prices = Collections.synchronizedSet(new HashSet<Integer>());
        CountDownLatch countDownLatch = new CountDownLatch(3);
        threadPool.execute(new Task(1, prices, countDownLatch));
        threadPool.submit(new Task(2, prices, countDownLatch));
        threadPool.submit(new Task(3, prices, countDownLatch));
        threadPool.submit(new Task(4, prices, countDownLatch));
        countDownLatch.await(30, TimeUnit.SECONDS);
        return prices;
    }


    static class Task implements Runnable {
        Integer productId;
        Set<Integer> prices;
        CountDownLatch countDownLatch;

        public Task(Integer productId, Set<Integer> prices, CountDownLatch countDownLatch) {
            this.productId = productId;
            this.prices = prices;
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(2000);
                prices.add(new Random().nextInt());
                countDownLatch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
